package com.ssh.controller;

import com.ssh.pojo.Dept;
import com.ssh.pojo.Employee;
import com.ssh.service.DeptService;
import com.ssh.service.EmployeeService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/emp")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private DeptService deptService;

    //去添加员工的页面
    @RequestMapping("/go_add.html")
    public ModelAndView goAdd() {
        List<Dept> deptList = deptService.getDeptList();
        return new ModelAndView("/emp_add.jsp", "deptList", deptList);
    }

    //添加员工
    @RequestMapping("/add.html")
    public String add(Employee employee, HttpServletRequest request) {
        try {
            employeeService.addEmployee(employee);
            request.setAttribute("message", "添加成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            request.setAttribute("message", "添加失败");
        }
        return "forward:/emp/go_add.html";
    }

    /**
     * @param employee 查询条件
     * @param map      向页面返回的数据
     * @return
     */
    @RequestMapping("/list.html")
    public String list(Employee employee, Map map) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Employee.class);
        if (employee != null) {
            //传了name代表名字查询
            if (employee.getName() != null && employee.getName().trim().length() > 0) {
                criteria.add(Restrictions.like("name", "%" + employee.getName() + "%"));
            }
            if (employee.getId() != null) {
                criteria.add(Restrictions.eq("id", employee.getId()));
            }
        }
        //执行查询
        List<Employee> employees = employeeService.getEmpList(criteria);
        map.put("employees", employees);//将查询结果传递给视图
        return "/emp_list.jsp";
    }
}
